from common.libs.Helper import selectFilterObj
from common.libs.Helper import getDictFilterFiled
from common.libs.Helper import ops_render
from common.models.pay import PayOrderItem
from common.models.pay import PayOrder
from common.models.food import Food
from common.models.member import Member
from application import app, db
from common.libs.Helper import getCurrentDate
from flask import Blueprint, request
from flask import jsonify
from sqlalchemy import func
import json

route_finance = Blueprint('finance_page', __name__)

@route_finance.route('/index')
def index():
    query = PayOrder.query
    resp = request.values
    status = resp.get('status', type=int)
    resp_data = {}

    # 搜索状态
    if status == -8:
        query = query.filter(PayOrder.status == -8)
    elif status == -7:
        query = query.filter(PayOrder.status == 1).filter(PayOrder.express_status == -7) \
            .filter(PayOrder.comment_status == 0)
    elif status == -6:
        query = query.filter(PayOrder.status == 1).filter(PayOrder.express_status == -6) \
            .filter(PayOrder.comment_status == 0)
    elif status == -5:
        query = query.filter(PayOrder.status == 1).filter(PayOrder.express_status == 1) \
            .filter(PayOrder.comment_status == 0)
    elif status == 1:
        query = query.filter(PayOrder.status == 1).filter(PayOrder.express_status == 1) \
            .filter(PayOrder.comment_status == 1)
    elif status == 0:
        query = query.filter(PayOrder.status == 0)

    # 指定当前页码
    page = resp.get('page', type=int)
    # 定义每页显示数
    page_size = app.config['PAGE_SIZE']
    page_url = request.full_path.replace('&page={}'.format(page), '')
    # 创建分页对象
    pagination = query.order_by(PayOrder.id.desc()).paginate(page, page_size, False)

    # 构建订单和美食的映射关系
    order_food_mapping = {}
    pay_order_list = PayOrder.query.order_by(PayOrder.id.desc()).all()

    for pay_order in pay_order_list:
        order_food_mapping[pay_order.id] = []
        pay_order_items = PayOrderItem.query.filter_by(pay_order_id=pay_order.id).all()
        food_ids = selectFilterObj(pay_order_items, 'food_id')
        food_mapping = getDictFilterFiled(Food, Food.id, 'id', food_ids)

        for item in pay_order_items:
            temp_food = food_mapping[item.food_id]
            order_food_mapping[pay_order.id].append({temp_food.name: item.quantity})

    resp_data['current'] = 'index'
    resp_data['page_url'] = page_url
    resp_data['search_val'] = resp
    resp_data['pagination'] = pagination
    resp_data['order_food_mapping'] = order_food_mapping
    resp_data['STATUS_LIST'] = app.config['PAY_ORDER_STATUS_MAPPING']

    return ops_render('finance/index.html', resp_data)

@route_finance.route('/account')
def account():
    resp_data = {}
    resp = request.values
    query = PayOrder.query.filter_by(status=1)

    # 指定当前页码
    page = resp.get('page', type=int)
    # 定义每页显示数
    page_size = app.config['PAGE_SIZE']
    page_url = request.full_path.replace('&page={}'.format(page), '')
    # 创建分页对象
    pagination = query.order_by(PayOrder.id.desc()).paginate(page, page_size, False)
    # 聚合查询
    total_money = db.session.query(func.sum(PayOrder.total_price).label('total')) \
        .filter(PayOrder.status == 1).first()

    resp_data['current'] = 'account'
    resp_data['page_url'] = page_url
    resp_data['total_money'] = total_money[0] if total_money[0] else 0.00
    resp_data['pagination'] = pagination

    return ops_render('finance/account.html', resp_data)

@route_finance.route('/pay-info')
def pay_info():
    resp_data = {}
    resp = request.values
    id = resp.get('id')

    pay_order_info = PayOrder.query.filter_by(id=id).first()
    member = Member.query.filter(Member.id == pay_order_info.member_id).first()
    express_info = json.loads(pay_order_info.express_info)

    pay_order_items = PayOrderItem.query.filter_by(pay_order_id=id).all()
    food_ids = selectFilterObj(pay_order_items, 'food_id')
    food_mapping = getDictFilterFiled(Food, Food.id, 'id', food_ids)

    resp_data['current'] = 'index'
    resp_data['member'] = member
    resp_data['express_info'] = express_info
    resp_data['food_mapping'] = food_mapping
    resp_data['pay_order_info'] = pay_order_info
    resp_data['pay_order_items'] = pay_order_items

    return ops_render('finance/pay_info.html', resp_data)

@route_finance.route('/ops', methods=['POST'])
def ops():
    result = {'code': 200, 'msg': '操作成功'}
    resp = request.values
    id = resp.get('id')
    if not id:
        result['code'] = -1
        result['msg'] = '发货失败！'
        return jsonify(result)

    pay_order = PayOrder.query.filter_by(id=id).first()

    # 修改快递的状态为待收货
    pay_order.express_status = -6
    pay_order.updated_time = getCurrentDate()
    pay_order.update()

    return jsonify(result)
